package com.mask.im.server.push;

import com.alibaba.fastjson.JSON;
import com.mask.im.server.constant.IMPushMessageConstant;
import com.mask.im.sdk.dto.IMPushMessage;
import com.mask.im.server.netty.IMChannelCtxMap;
import com.mask.im.server.netty.model.IMSendMessage;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

/**
 * 好友消息推送实现
 *
 * @author jian
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class IMSingleMessageProcessor extends IMAbstractPushMessage<IMPushMessage<Object>> {

    @Override
    public Boolean pushMessage(IMPushMessage<Object> receiveMessage) {
        log.info("接收到私聊消息，发送者:{},接收者:{}，内容:{}", receiveMessage.getSenderId(), receiveMessage.getReceiverId(), receiveMessage.getContent());
        try {
            Channel channel = IMChannelCtxMap.getUserIdChannel(receiveMessage.getReceiverId().toString());
            if (null != channel) {
                IMSendMessage imSendMessage = new IMSendMessage();
                imSendMessage.setCmd(IMPushMessageConstant.SINGLE_MESSAGE);
                imSendMessage.setData(receiveMessage.getContent());
                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(imSendMessage)));
                return true;
            }
            return false;
        } catch (Exception e) {
            // 消息推送失败确认
            log.error("好友消息发送异常", e);
            return false;
        }
    }
}
